package threadSafe;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.unsafe i++")
public class Demo {
//    static int count = 0;
//    static final Object lock = new Object();
//    static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        Room room = new Room();
        Thread t1 = new Thread(()->{
            for (int i = 1;i<5000;i++){
//                count++;
//                count.getAndIncrement();
//                synchronized (lock){
//                    count++;
//                }
                room.increment();
            }
        });
        Thread t2 =new Thread(()->{
            for (int i = 1;i<5000;i++){
//                count--;
//                count.getAndDecrement();
//                synchronized (lock){
//                    count--;
//                }
                room.decrement();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("count的值是{}",room.getCount());
    }
}

class Room{
    private int count = 0;
    public void increment(){
        synchronized (this){
            count++;
        }
    }
    public void decrement(){
        synchronized (this){
            count--;
        }
    }
    public int getCount(){
        synchronized (this){
            return count;
        }
    }
}